package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    private ElasticsearchTemplate esTemplate;


    @Override
    public Map search(Map<String, String> paramMap) {
        //新建返回参数
        Map<String , Object> resultMap = new HashMap<>();

        //有条件才查询
        if(paramMap.size() == 0){
            return null;
        }

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        queryBuilder.withQuery(boolQuery);

        //查询关键字
        if(StringUtils.isNotEmpty(paramMap.get("keywords"))){
            boolQuery.must(QueryBuilders.matchQuery("name",paramMap.get("keywords")).operator(Operator.AND));
        }
        //查询品牌
        if(StringUtils.isNotEmpty(paramMap.get("brand"))){
            boolQuery.filter(QueryBuilders.termQuery("brandName",paramMap.get("brand")));
        }

        //对品牌进行聚合查询
        String skuBrand = "skuBrand";
        queryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

        //按照商品规格信息进行查询
        for (String key : paramMap.keySet()) {
            if(key.startsWith("spec_")){
                //解决URL传参数据变化问题
                String value = paramMap.get(key).replace("%2B","+");
                //说明是规格信息
                boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
            }
        }

        //对商品搜索结果进行规格聚合处理
        String skuSpec = "skuSpec";
        queryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

        //对价格条件进行处理
        if(StringUtils.isNotEmpty(paramMap.get("price"))){
            //数据为 500-1000    3000-3500   4000等
            //对数据进行处理
            String[] p = paramMap.get("price").split("-");
            if(p.length == 2){
                boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
            }
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
        }



        //排序
        if(StringUtils.isNotEmpty(paramMap.get("sortField")) && StringUtils.isNotEmpty(paramMap.get("sortRule"))){
            if("ASC".equals(paramMap.get("sortRule"))){
                queryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.ASC));
            }else {
                queryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.DESC));
            }
        }

        //设置高亮域与高亮样式
        HighlightBuilder.Field fidld = new HighlightBuilder
                .Field("name")                       //设置高亮域名
                .preTags("<span style = 'color : red'>") //设置高亮域前缀
                .postTags("</span>");                      //设置高亮域后缀
        queryBuilder.withHighlightFields(fidld);
        //设置当前页和每页查询数量
        //第一个参数  当前页   从零开始
        //第二个参数  每页查询数量
        //分页
        String pageNum = paramMap.get("pageNum");
        String pageSize = paramMap.get("pageSize");
        if (StringUtils.isEmpty(pageNum)){
            pageNum = "1";
        }
        if (StringUtils.isEmpty(pageSize)){
            pageSize = "30";
        }
        queryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1,Integer.parseInt(pageSize)));

        //第一个参数： 条件构建对象
        //第二个参数： 查询操作实体类
        //第三个参数： 查询结果操作对象
        AggregatedPage<SkuInfo> resultInfo = esTemplate.queryForPage(queryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                //定义结果操作对象
                List<T> list = new ArrayList<>();
                SearchHits hits = searchResponse.getHits();

                //判断是否有查询命中值，如果有则进行封装
                if(hits != null) {
                    for (SearchHit hit : hits) {
                        SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                        //替换高亮域
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        if(highlightFields != null && highlightFields.size() > 0 ){
                            skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                        }
                        list.add((T) skuInfo);
                    }
                }
                return new AggregatedPageImpl<T>(list,pageable,hits.getTotalHits(),searchResponse.getAggregations());
            }
        });

        //总条数
        resultMap.put("total",resultInfo.getTotalElements());
        //总页数
        resultMap.put("totalPages",resultInfo.getTotalPages());
        //查询结果集合
        resultMap.put("rows",resultInfo.getContent());
        //获取品牌聚合结果
        StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
        List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
        resultMap.put("brandList",brandList);

        //获取规格聚合结果
        StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
        List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
        resultMap.put("specList",specFormat(specList));

        //返回当前页
        resultMap.put("pageNum",pageNum);
        return resultMap;
    }


    /**
     * 格式化spec规格，将List<String>类型转化为Map<String , Set<String>>类型
     * @param specList
     * @return
     */
    public Map<String , Set<String>> specFormat(List<String> specList){
        Map<String , Set<String>> resultMap = new HashMap<>();

        //判断specList是否有值
        if(specList != null && specList.size() > 0) {
            //获取List中每一行的数据
            for (String specString : specList) {
                //将每一行String数据转化为Map
                Map<String,String> specMap = JSON.parseObject(specString, Map.class);
                for (String specKey : specMap.keySet()) {
                    //将对应key的值添加进set
                    Set<String> specSet = resultMap.get(specKey);
                    //如果是第一次出现的key，则进行生成key
                    if(specSet == null){
                        specSet = new HashSet<>();
                    }
                    //将value添加进keySet
                    specSet.add(specMap.get(specKey));
                    //将keySet添加进Map
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;

    }
}
